package com.framework.service.impl;

import com.alibaba.druid.util.TransactionInfo;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.FlowFrozenTerminalDao;
import com.framework.entity.flow.FlowFrozenTerminal;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.ter.TerMerchantReport;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.entity.tran.TranTransactionInfo;
import com.framework.exception.RRException;
import com.framework.page.PageUtils;
import com.framework.service.*;
import com.framework.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 冻结流水
 *
 * @author wq
 */
@Service("flowFrozenTerminalService")
public class FlowFrozenTerminalServiceImpl extends ServiceImpl<FlowFrozenTerminalDao, FlowFrozenTerminal> implements FlowFrozenTerminalService {

    @Autowired
    private AgentService agentService;

    @Autowired
    private TerminalInfoService terminalInfoService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private DistribuService distribuService;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private TransactionInfoService transactionInfoService;



    @Override
    public Map<String, Object> queryFrozenDetail(String token) {

        SysAgent agent = agentService.queryAgentByToken(token);

        FlowFrozenTerminal terminal = selectOne(new EntityWrapper<FlowFrozenTerminal>().eq("agent_id", agent.getAgentId()));

        Map<String, Object> result = new HashMap<>(4);

        if (terminal != null) {
            result.put("name", agent.getName());
            result.put("phone", agent.getPhone());
            result.put("sn", terminal.getSn());
            String date;
            if (terminal.getState().intValue() == 1) {
                date = DateUtils.format(terminal.getThawTime(), DateUtils.DATE_PATTERN);
            } else {
                date = DateUtils.format(terminal.getCreateTime(), DateUtils.DATE_PATTERN);
            }
            result.put("frozenDate", date);
            result.put("state", terminal.getState());
        }

        return result;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("limit").toString());
        Integer currPage = Integer.valueOf(params.get("page").toString());
        params.put("start", (currPage - 1) * pageSize);
        params.put("limit", pageSize);
        List<Map<String, Object>> list = baseMapper.queryListForPage(params);
        Integer totalCount = baseMapper.queryCountForPage(params);
        return new PageUtils(list, totalCount, pageSize, currPage);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void thawFlag(Integer id, Integer flag) {
        FlowFrozenTerminal flow = new FlowFrozenTerminal();
        flow.setCountId(id);
        flow.setThawFlag(flag);
        updateById(flow);

    }

    @Override
    public FlowFrozenTerminal queryByAgentId(Long agentId) {
        return selectOne(new EntityWrapper<FlowFrozenTerminal>().eq("agent_id", agentId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addNewFrozen(Map<String, Object> params) {
        String sn = params.get("sn").toString();
        String name = params.get("name").toString();
        String phone = params.get("phone").toString();
        Long deptId= (Long) params.get("deptId");
        String model=params.get("model").toString();
        Integer terminalType= (Integer) params.get("terminalType");

        SysAgent agent=agentService.queryAgentByNameAndPhone(name,phone);

        FlowFrozenTerminal frozenTerminal = queryByAgentId(agent.getAgentId());

        if(frozenTerminal!=null){
            throw new RRException("9000","该合伙人已有冻结记录");
        }

        FlowFrozenTerminal f2=queryBySn(sn);
        if(f2!=null){
            throw new RRException("9000","该机器已参与冻结");
        }

        if(agent==null){
            throw new RRException("9000","无合伙人,请检查姓名与手机号码");
        }
        TerTerminalInfo info = terminalInfoService.queryTerminalBySn(sn);

        //处理机器
        if(info==null){
            info=new TerTerminalInfo();
            info.setActivationDate(new Date());
            info.setIsActivation(2);
            info.setMerchantCode(sn);
            info.setSn(sn);
            info.setIsActivation(2);
            info.setIsReport(2L);
            info.setTerminalType(terminalType);
            info.setModel(model);
            info.setDeptId(deptId);
            terminalInfoService.insert(info);
        }else {
            info.setIsReport(2L);
            info.setIsActivation(2);
            info.setActivationDate(new Date());
            terminalInfoService.updateById(info);
        }
        //处理分配
        distribuService.handleNewSn(agent.getAgentId(),info);

        //处理报备
        TerMerchantReport report=new TerMerchantReport();
        report.setPhone(phone);
        report.setMerchantName(name);
        report.setTerminalType(terminalType);
        report.setDeptId(deptId);
        report.setAgentId(agent.getAgentId());
        report.setCreateDate(new Date());
        report.setSn(sn);
        merchantService.insert(report);


        //冻结
        FlowFrozenTerminal flowFrozenTerminal=new FlowFrozenTerminal();
        flowFrozenTerminal.setAmount(new BigDecimal("3000"));
        flowFrozenTerminal.setCreateTime(new Date());
        flowFrozenTerminal.setDeptId(deptId);
        flowFrozenTerminal.setAgentId(agent.getAgentId());
        flowFrozenTerminal.setSn(sn);
        insert(flowFrozenTerminal);
        //达标
        agent.setStandardState(1);
        agentService.updateById(agent);

        agentInfoService.addFrozen(agent.getAgentId(),new BigDecimal("3000"));

        //处理交易
        List<TranTransactionInfo> list = transactionInfoService.queryListBySnAndTime(sn, DateUtils.addDateDays(new Date(),1));
        if(list==null || list.size()==0){
            TranTransactionInfo transactionInfo=new TranTransactionInfo();

            transactionInfo.setSn(sn);
            transactionInfo.setCreateDate(new Date());
            transactionInfo.setTransactionDate(new Date());
            transactionInfo.setIsBenefited(1);
            transactionInfo.setMerchantCode(sn);
            transactionInfo.setDeptId(deptId);
            transactionInfo.setTerminalType(terminalType);
            transactionInfo.setAmount(new BigDecimal("0.01"));
            transactionInfo.setIsVip("否");
            transactionInfoService.insert(transactionInfo);

        }

    }
    @Override
    public FlowFrozenTerminal queryBySn(String sn) {
        return selectOne(new EntityWrapper<FlowFrozenTerminal>().eq("sn", sn));
    }

}
